package com.ihr360.excel.service.impl;

import com.ihr360.excel.annotation.InterruptIgnore;
import com.ihr360.excel.dao.SpreadSheetRepository;
import com.ihr360.excel.model.dto.SpreadSheet;
import com.ihr360.excel.model.type.SpreadSheetStatus;
import com.ihr360.excel.service.SpreadsheetService;
import com.ihr360.excel.vo.ProgressContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author richey
 */
@Service
public class SpreadsheetServiceImpl implements SpreadsheetService {

    @Autowired
    private SpreadSheetRepository spreadSheetRepository;

    @Override
    @Transactional
    public void fineshedHistory(String progressKey) {
        spreadSheetRepository.fineshedHistory(progressKey, SpreadSheetStatus.FINISHED);
    }

    @Override
    @InterruptIgnore
    public synchronized SpreadSheet getOrAndCurrentSpreadsheet(ProgressContext progressContext) {
        SpreadSheet spreadSheet = spreadSheetRepository.findByProgressKeyAndStatus(progressContext.getProgressKey(), SpreadSheetStatus.INPROGRESS);
        if (spreadSheet == null) {
            spreadSheet = getSpreadSheet(progressContext, new Date());
            spreadSheet = spreadSheetRepository.save(spreadSheet);
        }
        return spreadSheet;
    }

    @Override
    @InterruptIgnore
    public synchronized SpreadSheet getCurrentSpreadsheet(ProgressContext progressContext) {
        SpreadSheet spreadSheet = spreadSheetRepository.findByProgressKeyAndStatus(progressContext.getProgressKey(), SpreadSheetStatus.INPROGRESS);
        return spreadSheet;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public SpreadSheet save(SpreadSheet spreadSheet) {
        return spreadSheetRepository.save(spreadSheet);
    }

    private SpreadSheet getSpreadSheet(ProgressContext progressContext, Date currentDate) {
        SpreadSheet spreadSheet = new SpreadSheet();
        spreadSheet.setFieldKey(progressContext.getFileId());
        spreadSheet.setCompanyId(progressContext.getCompanyId());
        spreadSheet.setProgressKey(progressContext.getProgressKey());
        spreadSheet.setCreatedAt(currentDate);
        spreadSheet.setUpdatedAt(currentDate);
        return spreadSheet;
    }

}
